<template>
  <div class="CustomerService">
    <!-- 粘性导航栏 -->
    <van-sticky>
      <!-- 绑定点击事件 -->
      <van-nav-bar title="智能客服" left-text="返回" left-arrow @click="fh" />
      
    </van-sticky>
    
    <!-- 聊天容器 -->
    <div class="chat-container">
      
      <!-- 渲染聊天记录 -->
      <template v-if="arr1.length > 0 && arr2.length > 0">
        <div v-for="(question, index) in arr1" :key="index">
          <div class="message sender">
            <p>{{ question }}</p>
          </div>
          <div style="clear: both;"></div>
          <div class="message receiver">
            <p>{{ arr2[index] }}</p>
          </div>
          <div style="clear: both;"></div>
        </div>
      </template>
      <!-- 显示等待提示 -->
      <p v-if="isWaitingResponse" style="text-align: center; margin-top: 10px;">请稍后，正在处理您的问题...</p>
      <div style="height: 100px;"></div>
    </div>
    <!-- 底部输入区域 -->
    <div class="CustomerService_footer">
      <textarea
        v-model="wt"
        @keydown="keyevent1"
        @keyup="keyevent2"
        placeholder="请输入问题"
      ></textarea>
      <button
        :class="{ button2: wt.length > 0, button1: wt.length === 0 }"
        @click="getChat"
      >
        发送
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';

// 引入样式

const router = useRouter();
const wt = ref('');
const arr1 = ref([]);
const arr2 = ref([]);
const isWaitingResponse = ref(false);

// 返回上一页的处理函数
const handleClick = () => {
  router.back();
};

const keyevent1 = (e) => {
  if (e.key === 'Enter') {
    getChat();
  }
};

const keyevent2 = (e) => {
  if (e.key === 'Enter') {
    wt.value = '';
  }
};

const getChat = async () => {
  isWaitingResponse.value = true;
  const currentInput = wt.value;
  arr1.value = [...arr1.value, currentInput];
  // 每次提问时，在 arr2 中添加一个空字符串元素，用于存储新的回答
  arr2.value = [...arr2.value, ''];
  wt.value = '';

  try {
    const response = await fetch('http://localhost:3000/getChat', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ content: currentInput })
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    let responseData = '';
    const reader = response.body.getReader();
    const decoder = new TextDecoder('utf-8');
    // 记录当前正在处理的回答在 arr2 中的索引
    const currentAnswerIndex = arr2.value.length - 1;

    while (true) {
      const { done, value } = await reader.read();
      if (done) {
        isWaitingResponse.value = false;
        break;
      }

      const chunk = decoder.decode(value);
      const lines = chunk.split('\n\n');
      lines.forEach(line => {
        if (line.startsWith('data:')) {
          try {
            const data = JSON.parse(line.slice(5));
            responseData += data.content;
            // 直接更新当前正在处理的回答
            arr2.value[currentAnswerIndex] = responseData;
            scrollToBottom();
          } catch (parseError) {
            console.error('Error parsing data:', parseError);
          }
        }
      });
    }
  } catch (error) {
    isWaitingResponse.value = false;
    console.error('Error fetching chat data:', error);
  }
};

const scrollToBottom = () => {
  const chatContainer = document.querySelector('.chat-container');
  if (chatContainer) {
    chatContainer.scrollTop = chatContainer.scrollHeight;
  }
};
const fh=()=>{
   router.back()
}
</script>

<style scoped>
/* 可以在这里添加局部样式 */
* {
    margin: 0;
    padding: 0;
}

.article_tabs {
  .ArticleDetails_box2{
    font-size: 24px;
  }
}

.article_box1 {
    width: 90%;
    margin: 0 auto;
    display: flex;
    justify-content: space-around;
    margin-top: 25px;

    .article_left {
        width: 35%;
        height: 100px;

        img {
            width: 100%;
            height: 100%;
            border-radius: 15%;
            object-fit: cover;
        }
    }

    .article_right {
        width: 55%;
        position: relative;

        .article_bottom_left {
            position: absolute;
            bottom: 0;
            left: 0;
        }

        .article_bottom_right {
            position: absolute;
            bottom: 0;
            right: 0;
        }
    }
}

.ArticleDetails_box1 {
    width: 90%;
    margin: 0 auto;
    
}

.ArticleDetails_box2 {
    width: 100%;
    display: flex;
    margin: 10px 0;
    position: relative;

    .ArticleDetails_box2_span1 {
        font-size: 24px;
        background-color: #CCCCCC;
        color: #666EE8;
        border-radius: 50%;
        padding: 5px;
        margin: 0 10px 0 0;
    }

    .ArticleDetails_box2_span2 {
        position: absolute;
        right: 0;

        button {
            width: 70px;
            background-color: #666EE8;
            color: white;
            border: 0;
            height: 30px;
        }
    }
}

.ArticleDetails_box3 {
    width: 100%;
    margin: 10px 0;

    img {
        width: 100%;
        height: 200px;
    }
}

.ArticleDetails_box4 {
    width: 100%;
    font-size: 14px;
    line-height: 24px;
}


.ArticleDetails_footer {
    font-size: 18px;
    position: fixed;
    bottom: 0;
    width: 100%;
    height: 50px;
    background-color: white;
    color: white;
    display: flex;
    justify-content: space-around;
    align-items: center;
    border-top: 1px solid #999999;
    color: gray;

    input {
        font-size: 16px;
        width: 40%;
        height: 30px;
        border: 0;
        background-color: #CCCCCC;
        color: white;
        padding-left: 10px;
    }
}

.popup_content {
    padding: 5px;
    color: gray;

    .popup_content_top {
        font-size: 16px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;
        border-bottom: 1px solid #999999;
        padding-bottom: 5px;
    }

    textarea {
        font-size: 16px;
        border: 0;
    }
}

.ArticleDetails_box5_all {
    display: flex;
    margin-top: 10px;

    .ArticleDetails_box5_left {
        text-align: center;
        font-size: 24px;
        width: 20%;
        background-color: rgb(205, 255, 238);
        color: #28D094;
        padding: 5px;
        margin-right: 10px;
    }

    .ArticleDetails_box5_right_all {
        width: 100%;
    }

    .ArticleDetails_box5_right {
        width: 100%;
        display: flex;
        justify-content: space-between;
    }
}

.ArticleDetails_box6_all {
    display: flex;
    margin-top: 10px;

    .ArticleDetails_box6_left {
        text-align: center;
        font-size: 24px;
        width: 20%;
        background-color: #c8caf3;
        color: #666EE8;
        padding: 5px;
        margin-left: 40px;
        margin-right: 10px;
    }

    .ArticleDetails_box6_right_all {
        width: 100%;
    }

    .ArticleDetails_box6_right {
        width: 100%;
        display: flex;
        justify-content: space-between;
    }
}

.CustomerService_footer {
    width: 100%;
    height: 45px;
    position: fixed;
    bottom: 10px;
    display: flex;
    justify-content: space-around;

    textarea {
        width: 70%;
        border: 0;
        background-color: #f3f3f3;
        font-size: 16px;
        padding-left: 10px;
        padding-top: 3px;
        padding-bottom: 3px;
    }

    .button1 {
        font-size: 24px;
        border: 0;
        padding: 10px;
        color: white;
        background-color: #cfcfcf;
        line-height: 20px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }

    .button2 {
        font-size: 24px;
        border: 0;
        padding: 10px;
        color: white;
        background-color: blue;
        line-height: 20px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }
}

.CustomerService_footer {
    width: 100%;
    height: 50px;
    position: fixed;
    bottom: 0px;
    display: flex;
    justify-content: space-around;
    background-color: white;

    textarea {
        width: 70%;
        height: 36px;
        background-color: #f3f3f3;
        font-size: 16px;
        padding-left: 10px;
        padding-top: 3px;
        padding-bottom: 3px;
        line-height:36px;
    }

    .button1 {
        font-size: 16px;
        height: 40px;
        border: 0;
        padding: 10px;
        color: white;
        background-color: #cfcfcf;
        line-height: 20px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }

    .button2 {
        font-size: 16px;
        height: 40px;
        border: 0;
        padding: 10px;
        color: white;
        background-color: blue;
        line-height: 20px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }
}

.CustomerService {
    font-family: Arial, sans-serif;
    background-color: #f2f2f2;
}

.chat-container {
    height: 740px;
    max-width: 400px;
    margin: 0 auto;
    padding: 20px;
    background-color: white;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.message {
    margin-bottom: 10px;
    padding: 8px 12px;
    border-radius: 8px;
    max-width: 70%;
}

.sender {
    background-color: #dcf8c6;
    float: right;
}

.receiver {
    background-color: #e6e6e6;
    float: left;
}
</style>